package org.libermundi.theorcs.core.tapestry.components;

import java.util.List;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.internal.InternalConstants;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONLiteral;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.libermundi.theorcs.core.tapestry.model.ContextMenuElement;

@Import(
	library={
			"${core.scripts}/jquery.contextmenu.js",
			"${core.scripts}/jquery.contextmenu.init.js"
	},
	stack=InternalConstants.CORE_STACK_NAME,
	stylesheet="${core.styles}/jquery.contextmenu.css"
)
public class ContextMenu {
	@Parameter
	private List<ContextMenuElement> _menuElements;
	
	@Parameter(defaultPrefix=BindingConstants.LITERAL)
	private String _bindTo;
	
	@Parameter(defaultPrefix=BindingConstants.LITERAL)
	private String _handler;
	
	@Property
	private ContextMenuElement _element;
	
	@Inject
	private JavaScriptSupport _jsSupport;
	
	public String getElementClass() {
		String css = _element.getAction();
		if(_element.hasSeparator()) { 
			css += " separator";
		}
		return css;
	}
	
	@AfterRender
	public void afterRender() {
		StringBuilder items = new StringBuilder();
		int i=0;
		boolean init=Boolean.TRUE;
		items.append("{"); // Must use this way in order to get the JSON Object with the right order.
		for (ContextMenuElement element : _menuElements) {
			if(!init){
				items.append(",");
			}
			items.append("\"" + element.getAction() + "\":" + "{");
			items.append("\"name\":"+"\"" + element.getLabel() + "\",\"icon\":" + "\"" + element.getAction() + "\",\"disabled\": true");
			items.append("}");
			if(element.hasSeparator()){
				items.append("," + "\"sep" + i + "\":" + "\"-------\"");
				i++;
			}
			init=false;
		}
		items.append("}");
		JSONObject params = new JSONObject();
			params.put("selector",_bindTo);
			params.put("handler",_handler);
			params.put("items",new JSONLiteral(items.toString()));
		_jsSupport.addInitializerCall("initContextualMenu", params);
	}

}
